from rest_framework import serializers
from django.contrib.auth import get_user_model

User = get_user_model()


class RegisterSerializer(serializers.ModelSerializer):
    password = serializers.CharField(write_only=True, min_length=6)
    password2 = serializers.CharField(write_only=True, min_length=6)  # 新增确认密码字段

    class Meta:
        model = User
        fields = ['username', 'password', 'password2']

    def validate(self, data):
        """
        校验密码是否一致
        """
        if data['password'] != data['password2']:
            raise serializers.ValidationError({"password": "两次输入的密码不一致！"})
        return data

    def create(self, validated_data):
        validated_data.pop('password2')
        user = User.objects.create_user(
            username=validated_data['username'],
            password=validated_data['password']
        )
        return user


class UserSerializer(serializers.ModelSerializer):
    avatar_url = serializers.SerializerMethodField(read_only=True)  # 用于返回图片 URL

    class Meta:
        model = User
        fields = ['id', 'username', 'nickname', 'email', 'phone','avatar', 'avatar_url', 'biography']
        read_only_fields = ['id', 'username', 'avatar_url']

    def get_avatar_url(self, obj):
        if obj.avatar:
            request = self.context.get('request')
            return request.build_absolute_uri(obj.avatar.url) if request else obj.avatar.url
        return None
